# Generate SSL certificates for WebRTC project

Write-Host "Generating SSL certificates..." -ForegroundColor Green

# Create directories
New-Item -ItemType Directory -Force -Path "nginx\ssl" | Out-Null
New-Item -ItemType Directory -Force -Path "certs" | Out-Null

# Check if OpenSSL is available
try {
    $null = Get-Command openssl -ErrorAction Stop
    $useOpenSSL = $true
    Write-Host "Using OpenSSL..." -ForegroundColor Yellow
}
catch {
    $useOpenSSL = $false
    Write-Host "OpenSSL not found, using PowerShell..." -ForegroundColor Yellow
}

if ($useOpenSSL) {
    # Generate certificate with OpenSSL
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout nginx/ssl/key.pem -out nginx/ssl/cert.pem -subj "/C=CN/ST=Beijing/L=Beijing/O=WebRTC/CN=localhost"
    
    # Generate PFX for ASP.NET Core
    openssl pkcs12 -export -out certs/aspnetapp.pfx -inkey nginx/ssl/key.pem -in nginx/ssl/cert.pem -passout pass:
}
else {
    # Use PowerShell to generate certificate
    $cert = New-SelfSignedCertificate -DnsName "localhost" -CertStoreLocation "cert:\CurrentUser\My"
    
    # Export as PFX
    $password = ConvertTo-SecureString -String "" -Force -AsPlainText
    Export-PfxCertificate -Cert $cert -FilePath "certs\aspnetapp.pfx" -Password $password | Out-Null
    
    # Export as PEM (simplified)
    $certBase64 = [System.Convert]::ToBase64String($cert.Export('Cert'))
    $pemContent = "-----BEGIN CERTIFICATE-----`n$certBase64`n-----END CERTIFICATE-----"
    Set-Content -Path "nginx\ssl\cert.pem" -Value $pemContent
    
    # Create placeholder key file
    $keyContent = "-----BEGIN PRIVATE KEY-----`n# Placeholder key - install OpenSSL for real key`n-----END PRIVATE KEY-----"
    Set-Content -Path "nginx\ssl\key.pem" -Value $keyContent
    
    # Clean up certificate store
    Remove-Item "cert:\CurrentUser\My\$($cert.Thumbprint)" -ErrorAction SilentlyContinue
    
    Write-Host "Warning: Using placeholder key file" -ForegroundColor Yellow
    Write-Host "Install OpenSSL for production use: winget install OpenSSL.OpenSSL" -ForegroundColor Cyan
}

Write-Host "Certificate generation completed!" -ForegroundColor Green
Write-Host "Files created:" -ForegroundColor Cyan
Write-Host "  nginx/ssl/cert.pem" -ForegroundColor White
Write-Host "  nginx/ssl/key.pem" -ForegroundColor White  
Write-Host "  certs/aspnetapp.pfx" -ForegroundColor White 